<?php
namespace Platform\Common;

use Platform\Model\AdminToken as AdminTokenModel;
use Platform\Model\Admin as AdminModel;
use Platform\Model\AdminRole as AdminRoleModel;
use PhalApi\Exception\BadRequestException;

/**
 * 管理员会话服务
 * @author zh
 */
class Admin {

    public function __construct() {
    }

    /**
     * 退出登录，清除会话
     */
    public function logout() {
        $tokenModel = new AdminTokenModel();
        //根据当前token值设置过期时间为退出时间
        $sign = $_SERVER['HTTP_AUTHORIZATION'];
        if( empty( $sign ) ){
            throw new BadRequestException('token验证失败！', 8);
        }
        $sign = explode(' ',$sign);
        $res = $tokenModel->updateAll(array('token'=>$sign[1]),array('invalid_time'=>time()-1));
        if( empty( $res ) ){
            throw new BadRequestException('退出失败！', 8);
        }
    }

    /**
     * 检测是否登录
     */
    public function check($isStopIfNoLogin = TRUE) {
        //增加header头验证
        $tokenModel = new AdminTokenModel();
        $AdminModel = new AdminModel();
        $AdminRoleModel = new AdminRoleModel();
        //获取header里的参数Authorization
        //如果header里放入的值为Authorization，到header里会自动加上HTTP_，并且转化为大写，取值时如下
        $sign = $_SERVER['HTTP_AUTHORIZATION'];
        if( empty( $sign ) ){
            throw new BadRequestException('token验证失败！', 8);
        }
        $sign = explode(' ',$sign);
        $tokenData = $tokenModel->getData(array('token'=>$sign[1]));
        if (!empty($tokenData)&&$tokenData['invalid_time']>time()) {
            //根据user_id查询用户的基本信息
            $userData = $AdminModel->get($tokenData['user_id']);
            //根据role_id查询角色名称
            $role_info = $AdminRoleModel->get($userData['role_id']);
            //根据前端项目需求将roles变成数组
            $userData['roles'] = explode(',',$userData['role_id']);
            $userData['role_name'] = $role_info['role_name'];
            //处理商家信息分组
            //查询可管理的后台用户列表
            $where = array();
            if( $role_info['role_name'] != '超级管理员' ){
                $where['add_who = ? or id = ?'] = array($userData['id'],$userData['id']);
            }
            $where['delete_flag'] = 'N';
            $where['not role_id'] = array(1);
            $list = $AdminModel->getList($where,array(),'id,name');
            $userData['user_list'] = $list;
            return $userData;
        }
        if ($isStopIfNoLogin) {
            throw new BadRequestException('登录已过期，请重新登录！', 8);
        }
        return FALSE;
    }
}